import { Injectable, HttpException, Logger, HttpCode } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { UserEntity } from '@src/entities/user.entity';
import { LoginDto } from '@src/controllers/admin/login/dto/login.dto';
import { ToolService } from '../tool/tool.service';

@Injectable()
export class UserService {
  constructor (
    @InjectRepository(UserEntity)
    private readonly userRepository: Repository<UserEntity>,
    private readonly toolService: ToolService,
  ) { }


  async userList(): Promise<any> {
    const userList = await this.userRepository.find();
    return userList.map(item => item.toResponseObject(false));
  }

  async userDetails(id: number): Promise<any> {
    const user = await this.userRepository.findOne({ id });
    return user.toResponseObject(false);
  }

  async createUser(data: any): Promise<any> {
    try {
      const user = this.userRepository.create(data);
      const result: any = await this.userRepository.save(user);
      return result.toResponseObject(false);
    } catch (e) {
      Logger.error(e);
      throw new HttpException('创建错误', 200);
    }
  }

  async modifyUser(id: number, data: any): Promise<any> {
    return await this.userRepository.update({ id }, data);
  }

  async deleteUser(id: number): Promise<any> {
    return await this.userRepository.delete({ id });
  }


  async login(loginDto: LoginDto): Promise<any> {
    const { username, password } = loginDto;
    const user = await this.userRepository.findOne({ username });
    if (user && this.toolService.checkPassword(password, user.password)) {
      return user.toResponseObject(true);
    } else {
      throw new HttpException('登录失败: 用户名或者密码错误', 200);
    }
  }
}
